package main

import (
	"bufio"
	"bytes"
	"context"
	"encoding/json"
	"io"
	"log"
	"net/http"
	"time"
)

// SearchRequest 是请求参数的结构体
type SearchRequest struct {
	RepoTag    string `json:"repoTag"`
	IsOfficial bool   `json:"isOfficial"`
}

func main() {
	// 创建请求参数
	reqData := SearchRequest{
		RepoTag:    "mysql",
		IsOfficial: true,
	}

	// 将请求参数编码为 JSON
	reqBody, err := json.Marshal(reqData)
	if err != nil {
		log.Fatalf("Error marshaling request data: %v", err)
	}

	// 创建请求
	url := "http://127.0.0.1:5555/v1/images/search"
	req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(reqBody))
	if err != nil {
		log.Fatalf("Error creating request: %v", err)
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "text/event-stream")

	// 创建 HTTP 客户端
	client := &http.Client{
		Timeout: 10 * time.Minute,
	}

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		log.Fatalf("Error sending request: %v", err)
	}
	defer resp.Body.Close()

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		log.Fatalf("Unexpected status code: %d", resp.StatusCode)
	}

	// 处理 SSE 响应
	ctx, cancel := context.WithCancel(context.Background())
	go handleEvents(ctx, resp.Body)

	// 模拟长时间运行的客户端
	time.Sleep(30 * time.Second)

	// 取消上下文，关闭连接
	cancel()
}

// handleEvents 处理 SSE 事件
func handleEvents(ctx context.Context, body io.ReadCloser) {
	reader := bufio.NewReader(body)
	for {
		select {
		case <-ctx.Done():
			log.Println("Context canceled, stopping event handling")
			return
		default:
			line, err := reader.ReadString('\n')
			if err != nil && err != io.EOF {
				log.Printf("Error reading event: %v", err)
				return
			}
			log.Printf(line)
			if err == io.EOF {
				log.Println("End of stream")
				return
			}
		}
	}
}
